package ai.example.langchain4j.store;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

//确定使用这个方案的话，可以换成redis + mysql 存储长短期的对话
@Component
public class InMemoryChatMemoryStore implements ChatMemoryStore {

    private static final int MAX_SESSIONS = 1000; // 最多保留 1000 个会话
    private final LinkedHashMap<String, List<ChatMessage>> memory = new LinkedHashMap<>();

    @Override
    public synchronized List<ChatMessage> getMessages(Object sessionId) {
        return memory.getOrDefault(sessionId.toString(), new LinkedList<>());
    }

    @Override
    public synchronized void updateMessages(Object sessionId, List<ChatMessage> messages) {
        memory.put(sessionId.toString(), messages);

        // 超过上限时删除最早插入的会话
        while (memory.size() > MAX_SESSIONS) {
            String oldestKey = memory.keySet().iterator().next();
            memory.remove(oldestKey);
        }
    }

    @Override
    public synchronized void deleteMessages(Object sessionId) {
        memory.remove(sessionId.toString());
    }
}

